<template>
  <div>
    <div id="mapContainer"></div>

      <el-card id="extend" v-show="!isHidden" @click="hidden">+</el-card>
    <el-card id="dataCard" v-show="isHidden">
      <div id="hiddenButton" @click="hidden">-</div>
      <el-tabs v-model="activeName">
        <!-- 表格展示区 -->
        <el-tab-pane
          label="表格"
          name="table"
        >
          <el-table
            :data="epidemicData.data"
            height="50vh"
            border
            row-key="xArea"
            :tree-props="{ children: 'subList' }"
          >
            <el-table-column
              prop="xArea"
              label="地区"
              width="100"
            />
            <el-table-column
              prop="curConfirm"
              label="当前确诊"
              width="100"
            />
            <el-table-column
              prop="confirm"
              label="全部病例"
              width="100"
            />
            <el-table-column
              prop="heal"
              label="治愈"
              width="100"
            />
            <el-table-column
              prop="died"
              label="死亡"
              width="100"
            />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 图例 -->
    <div class="mapDeference">
      <div
        class="mapDeference-item"
        style="backgroundColor: rgba(255, 0, 0, 1);"
      ></div>
      <div
        class="mapDeference-item"
        style="backgroundColor: rgba(255, 0, 0, 0.75);"
      ></div>
      <div
        class="mapDeference-item"
        style="backgroundColor: rgba(255, 0, 0, 0.5);"
      ></div>
      <div
        class="mapDeference-item"
        style="backgroundColor: rgba(255, 0, 0, 0.35);"
      ></div>
      <div
        class="mapDeference-item"
        style="backgroundColor: rgba(255, 0, 0, 0.25);"
      ></div>
    </div>
    <div class="mapDeference-digital">
      <div class="mapDeference-item">1000</div>
      <div class="mapDeference-item">500</div>
      <div class="mapDeference-item">100</div>
      <div class="mapDeference-item">50</div>
      <div class="mapDeference-item">10</div>
    </div>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  onActivated,
  onDeactivated,
  watch,
  onMounted,
  nextTick,
  h,
} from "vue";
import { shallowRef } from "@vue/reactivity";
// import { createRegion } from "@/tools/createRegion.js";
import { ElMessage } from "element-plus";
// import * as echarts from "echarts";
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";
import { getEpidemicDataReq } from "@/networks/getEpidemicData.js";
window._AMapSecurityConfig = {
  //高德地图API安全码
  securityJsCode: "7a147469fc71afc2c2540196e2453b2b",
};

let map = shallowRef(null); //地图容器
let epidemicData = reactive({ data: null });
let activeName = ref("table");
let isHidden = ref(true);
function hidden() {
  isHidden.value = !isHidden.value;
}
// 加载地图
let initMap = function () {
  if (map.value != null) {
    map.value?.destroy();
    map.value?.clearMap();
  }
  AMapLoader.load({
    key: "2b45c6a7655404e69a9b856504d8625c", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
  }).then((AMap) => {
    // 创建行政区边界
    let colors = {};
    let adcodeCity = {
      520000: "贵州", //贵州
      540000: "西藏", //西藏
      530000: "云南", //云南
      500000: "重庆", //重庆
      360000: "江西", //江西
      340000: "安徽", //安徽
      510000: "四川", //四川
      350000: "福建", //福建
      430000: "湖南", //湖南
      420000: "湖北", //湖北
      410000: "河南", //河南
      330000: "浙江", //浙江
      640000: "宁夏", //宁夏
      650000: "新疆", //新疆
      440000: "广东", //广东
      370000: "山东", //山东
      450000: "广西", //广西
      630000: "青海", //青海
      320000: "江苏", //江苏
      140000: "山西", //山西
      460000: "海南", // 海南
      310000: "上海", //上海
      110000: "北京", // 北京
      130000: "河北", // 河北
      230000: "黑龙江", // 黑龙江
      220000: "吉林", // 吉林
      210000: "辽宁", //辽宁
      150000: "内蒙古", //内蒙古
      120000: "天津", // 天津
      620000: "甘肃", // 甘肃
      610000: "甘肃", // 甘肃
      710000: "台湾", //台湾
      810000: "香港", //香港
      820000: "澳门", //澳门
    };
    let provinceArea = new AMap.DistrictLayer.Country({
      zIndex: 10,
      SOC: "CHN",
      depth: 1,
      styles: {
        "nation-stroke": "#409EFF",
        "coastline-stroke": "#409EFF",
        "province-stroke": "grey",
        fill: function (props) {
          return getColor(props.adcode_pro);
        },
      },
    });

    map.value = new AMap.Map("mapContainer", {
      zooms: [4, 10],
      center: [75.122082, 33.719192],
      zoom: 4,
      isHotspot: false,
      defaultCursor: "pointer",
      layers: [provinceArea],
      viewMode: "3D",
    });

    AMap.plugin(
      [
        "AMap.ToolBar",
        "AMap.Geolocation",
        "AMap.DistrictSearch",
        "AMap.InfoWindow",
        "AMap.DistrictLayer",
      ],
      async function () {}
    );

    // 根据病例数量及地区风险等级，改变地图区域颜色
    function getColor(adcode) {
      if (!adcode) {
        return;
      } else {
        let city = adcodeCity[adcode];
        epidemicData.data.map((item) => {
          if (item.xArea == city) {
            if (item.curConfirm >= 0 && item.curConfirm <= 10) {
              colors[adcode] = "rgba(255,0,0,0.25)";
            } else if (item.curConfirm > 10 && item.curConfirm <= 50) {
              colors[adcode] = "rgba(255,0,0,0.35)";
            } else if (item.curConfirm > 50 && item.curConfirm <= 100) {
              colors[adcode] = "rgba(255,0,0,0.5)";
            } else if (item.curConfirm > 100 && item.curConfirm <= 500) {
              colors[adcode] = "rgba(255,0,0,0.75)";
            } else if (item.curConfirm > 500) {
              colors[adcode] = "rgba(255,0,0,1)";
            }
          }
        });
      }
      return colors[adcode];
    }

    // 监听地图点击
    map.value.on("click", async (e) => {
      // console.log(e);
      let lnglat = e.lnglat;
      const { data: res } = await axios.get(
        `https://restapi.amap.com/v3/geocode/regeo?key=f58766337111f56d9101db384fbea982&location=${lnglat.lng},${lnglat.lat}`
      ); //获取结构化地址
      if (res.status != "1") {
        return ElMessage.error("编码转换失败");
      }
      let province = res.regeocode.addressComponent.province;

      epidemicData.data.map(async (item) => {
        // console.log(item.xArea,province)
        let ex = new RegExp(item.xArea);
        if (ex.test(province)) {
          let infoWindow = new AMap.InfoWindow({
            anchor: "top-left",
            content: `
            <div style="display: flex;align-item: center;flex-direction: column">
              <div style="color: red;font-size: 1rem;margin:2px 1px;">${item.xArea}</div>
              <div style="color: red;font-size: 0.5rem;margin:2px 1px;">当前确诊：${item.curConfirm}</div>
              <div style="color: red;font-size: 0.5rem;margin:2px 1px;">总计确诊：${item.confirm}</div>
              <div style="color: red;font-size: 0.5rem;margin:2px 1px;">无症状感染者：${item.asymptomatic}</div>
              <div style="color: red;font-size: 0.5rem;margin:2px 1px;">治愈：${item.heal}</div>
              <div style="color: red;font-size: 0.5rem;margin:2px 1px;">死亡：${item.died}</div>
              <div style="color: red;font-size: 0.5rem;margin:2px 1px;">${item.noNativeRelativeDays}</div>

            </div>
              
            `,
          });
          await createRegion(province, map.value);
          infoWindow.open(map.value, [lnglat.lng, lnglat.lat]);
        }
      });
    });

    // 创建区域
    async function createRegion(regionName, map, level) {
      //获取行政区划
      map.clearMap();
      if (regionName == null) {
        return;
      }
      let district = new AMap.DistrictSearch({
        // 返回行政区边界坐标等具体信息
        extensions: "all",
        // 设置查询行政区级别为 区
        level: level == null ? "district" : level,
      });
      await district.search(regionName, function (status, result) {
        // 获取合肥市的边界信息
        var bounds = result.districtList[0].boundaries;
        var polygons = [];
        if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
            //生成行政区划polygon
            var polygon = new AMap.Polygon({
              map: map,
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.7,
              fillColor: "#409EFF",
              strokeColor: "#CC66CC",
            });
            polygons.push(polygon);
          }
          // 地图自适应
          // map.setFitView();
        }
      });
    }
  });
};

// 获取数据
async function getEpidemicData() {
  try {
    // let { data: res } = await axios.get(
    //   `http://localhost:3000/api/epidemic_situation?appid=15877&sign=3fedaa8ff5e1535dfd491a3a9a076bd0`
    // );

    let { data: res } = await getEpidemicDataReq({
      appid: 15877,
      sign: "3fedaa8ff5e1535dfd491a3a9a076bd0",
    });
    if (res.codeid != "10000") {
      console.log(res);
      return ElMessage.error("获取数据失败");
    }
    epidemicData.data = res.retdata;
    // console.log(epidemicData.data);
    ElMessage.success("更新成功");
  } catch (err) {
    ElMessage.error("获取数据失败");
    console.log(err);
  }
}

// 生命周期

onActivated(async () => {
  await getEpidemicData(); //获取疫情数据
  initMap();
});

onDeactivated(() => {
  map.value?.destroy();
  map.value?.clearMap();
});
</script>

<script>
export default {
  name: "epidemic_situation",
  data() {
    return {};
  },
  methods: {},
};
</script>

<style lang="less" scoped>
#mapContainer {
  width: calc(100vw - 200px);
  height: calc(100vh - 3rem);
  position: absolute;
  top: 3rem;
  left: 200px;
}

#dataCard {
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
}

.mapDeference {
  position: absolute;
  z-index: 2;
  width: 20px;
  height: 100px;
  bottom: 20px;
  right: 40px;
  border: 1px solid black;
  .mapDeference-item {
    width: 20px;
    height: 20px;
  }
}

.mapDeference-digital {
  position: absolute;
  z-index: 2;
  width: 20px;
  height: 100px;
  bottom: 20px;
  right: 80px;

  .mapDeference-item {
    width: 20px;
    height: 20px;
    font-size: 0.1rem;
  }
}

#hiddenButton {
  position: absolute;
  right: 20px;
  font-size: 3rem;
  top: -10px;
  cursor: pointer;
  z-index: 20;
}

#extend {
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
  font-size: 2rem;
  cursor: pointer;
}

.el-tabs__header{
  z-index: 10;
}
</style>
